package unimelb.filesync.server.protocol;

import java.security.KeyPair;

import javax.crypto.SecretKey;

import unimelb.filesync.common.crypto.CryptoUtils;
import unimelb.filesync.common.message.NetworkMessage;
import unimelb.filesync.common.message.SecretKeyMsg;
import unimelb.filesync.common.misc.ProtocolContext;
import unimelb.filesync.common.network.NetworkConnection;
import unimelb.filesync.common.network.NetworkService;
import unimelb.filesync.common.network.RsaEncryptedNetworkConnection;
import unimelb.filesync.common.protocol.IFileSyncPhase;

public class GetSecretKeyPhase implements IFileSyncPhase {
    private final ProtocolContext context;

    private final CryptoUtils cryptoUtils;

    private final NetworkService networkService;

    public GetSecretKeyPhase(ProtocolContext context) {
        super();
        this.context = context;
        this.cryptoUtils = new CryptoUtils();
        this.networkService = new NetworkService();
    }

    @Override
    public void execute() {
        System.out.println("Reading secret key and init vector");

        final KeyPair keyPair = context.getObject(ProtocolContext.SERVER_KEY_PAIR);
        final NetworkConnection unsecuredConnection = context.getObject(ProtocolContext.HOT_LINE_CONNECTION);
        final NetworkConnection securedConnection = new RsaEncryptedNetworkConnection(unsecuredConnection, keyPair.getPrivate());
        
        final NetworkMessage msg = networkService.readMessage(securedConnection);
        if (msg == null) {
            System.exit(0);
        }

        final SecretKeyMsg content = msg.getContent();
        final SecretKey secretKey = cryptoUtils.decodeSecretKey(content.getSecretKey());

        context.addObject(ProtocolContext.SECRET_KEY, secretKey);
    }
}
